<template>
  <ArticleForm v-model="form" mode="edit" @save="handleSave" />
</template>

<script setup lang="ts">
import {  reactive, onMounted } from 'vue';
import { useRequest } from '@/composables/useRequest';
import { useArticleAutoSave } from './hooks/useArticleAutoSave';
import { useRoute, useRouter } from 'vue-router';
import ArticleForm from './components/ArticleForm.vue';
import { getArticleById, updateMyPiece } from '@/api/piece';
import type { addUpdateMyPieceRequest } from '@/types/piece';
import { ElMessage } from 'element-plus';
import { ArticleContentType } from '@/constant/article';

const route = useRoute();
const router = useRouter();
const articleId = route.params.id as string;

const form = reactive<addUpdateMyPieceRequest>({
  title: '',
  tags: [],
  cover_image: '',
  category: '',
  desc: '',
  visible: '',
  content: '',
  content_type: ArticleContentType.HTML,
  status: 'draft'
});

const { run } = useRequest();

// 自动保存，每30秒调用一次 handleSave
useArticleAutoSave(form, (data) => handleSave(data, true), 30000);

onMounted(async() => {
  if (articleId) {
    const res = await getArticleById(articleId);
    if (res && res.data) {
      Object.assign(form, {
        ...res.data,
        tags: res.data.tags ? res.data.tags.map((tag: { name: string }) => tag.name) : [],
        editorValue:
          res.data.content_type === ArticleContentType.HTML ? res.data.content : '',
        articleContent:
          res.data.content_type === ArticleContentType.MARKDOWN ? res.data.content : ''
      });
    }
  }
});

async function handleSave(val: addUpdateMyPieceRequest, isAuto = false) {
  await run(() => updateMyPiece(articleId, val), {
    onSuccess: () => {
      if (isAuto) {
        ElMessage.success('自动保存成功');
      } else {
        ElMessage.success('文章更新成功');
        router.back();
      }
    },
    onError: (err) => {
      if (isAuto) {
        console.warn('自动保存失败:', err);
      } else {
        ElMessage.error('文章更新失败');
      }
    }
  });
}
</script>

<style scoped></style>
